import React, { useState, useEffect } from "react";
import { NavBar, Grid, Tabs, Card } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import styles from "../style/score.module.css";
import scoree from "../img/score.png";
import next from "../img/next.png";
import hot from "../img/hot.png";
import juli from "../img/juli.png";
import { score } from "../api/score";
import scorecart from "../img/scorecart.png";
import scoreYE from '../img/scoreYE.png'
// 直接在组件文件中定义类型
interface Product {
  id: string | number;
  img: string;
  title: string;
  points: number;
  price?: number;
  original_price?: number;
  synopsis?: string;
}

interface ProductType {
  id: string | number;
  title: string;
  sub_title: string;
}

interface ScoreData {
  score: number;
  types: ProductType[];
  products: Product[];
  hotProducts: Product[];
}

const ScorePage = () => {
  const navigate = useNavigate();
  const [scoreData, setScoreData] = useState<ScoreData>({
    score: 0,
    types: [],
    products: [],
    hotProducts: [],
  });
  const [activeTab, setActiveTab] = useState<string | number>("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchScoreData();
  }, []);
  const user = JSON.parse(localStorage.getItem("user") || "null"); //用户数据
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");
  const fetchScoreData = async () => {
    try {
      const response = await score({
        user_id: user.data.id,
      });
      console.log(response.data, "数据");

      if (response.data.code === 1) {
        const data = response.data.data;
        setScoreData({
          score: data.score || 0,
          types: data.type || [],
          products: data.list || [],
          hotProducts: data.hotProducts || [],
        });
        if (data.type.length > 0) {
          setActiveTab(data.type[0].id);
        }
      }
      setLoading(false);
    } catch (error) {
      console.error("请求失败:", error);
      setLoading(false);
    }
  };

  const handleTabChange = (key: string | number) => {
    setActiveTab(key);
    // 这里可以添加分类切换后的数据加载逻辑
  };
  const handleshopClick = (product: Product) => {
    localStorage.setItem(
      "currentProduct",
      JSON.stringify({
        productId: product.id,
        productImg: product.img,
        productPrice: product.price,
        productTitle: product.title,
      })
    );

    navigate("/productDetailPage");
  };
  const renderHotProducts = () => {
    const sortedHotProducts = [...scoreData.hotProducts].sort((a, b) => {
      const priceA = a.price || 0;
      const priceB = b.price || 0;
      return priceB - priceA;
    });
    const topTwoProducts = sortedHotProducts.slice(0, 2);

    console.log("scoreData.hotProducts:", scoreData.hotProducts);
    console.log("topTwoProducts:", topTwoProducts);

    if (topTwoProducts.length === 0) {
      return <div className={styles.emptyState}>暂无热门商品</div>;
    }

    return (
      <Grid columns={2} gap={8}>
        {topTwoProducts.map((product: Product) => (
          <Grid.Item key={product.id}>
            <div className={styles.productCard}>
              <img src={product.img} alt={product.title} />
              <h4>{product.title}</h4>
              <div className={styles.price}>
                <span>积分 {product.price}</span>
                <button className={styles.exchangeBtn}>兑换</button>
              </div>
            </div>
          </Grid.Item>
        ))}
      </Grid>
    );
  };

  const renderProducts = () => (
    <Grid columns={2} gap={8}>
      {scoreData.products.map((product: Product) => (
        <Grid.Item key={product.id} onClick={() => handleshopClick(product)}>
          <div className={styles.productCard}>
            <img src={product.img} alt={product.title} />
            <h4>{product.title}</h4>
            <div className={styles.price}>
              <span className={styles.jifen}>
                <img
                  src={scoreYE}
                  alt=""
                />{" "}
                {product.price}
              </span>
              <div className={styles.exchangeBtn}>
                <img
                  src={scorecart}
                  alt=""
                />
              </div>
            </div>
          </div>
        </Grid.Item>
      ))}
    </Grid>
  );
  const ranking = () => {
    navigate("/ranking");
  };
  return (
    <div className={styles.container}>
      <NavBar onBack={() => navigate("/me")}>积分中心</NavBar>

      <div className={styles.content}>
        <Card className={styles.scoreCard}>
          <div className={styles.scoreHeader}>
            <div className={styles.scoretop}>
              <h3>我的积分</h3>
              <div className={styles.ranking} onClick={ranking}>
                排行榜
              </div>
            </div>
            <div className={styles.scoreValue}>
              <div className={styles.scoreValueji}>
                <img src={scoree} alt="积分" />
                <span>{scoreData.score}</span>
              </div>
              <div
                className={styles.scoreDetail}
                onClick={() => navigate("/scoreDetails")}
              >
                明细 <img src={next} alt="更多" />
              </div>
            </div>
          </div>
          <div className={styles.notice}>签到可获得积分奖励，全平台通用</div>
        </Card>

        <Card
          title={
            <div className={styles.hotTitle}>
              <img src={hot} alt="hot" />
              超值限时兑
            </div>
          }
        >
          <img className={styles.productImgs} src={juli} alt="" />
          {renderHotProducts()}
        </Card>

        <Tabs activeKey={activeTab.toString()} onChange={handleTabChange}>
          {scoreData.types.map((type: ProductType) => (
            <Tabs.Tab
              key={type.id.toString()}
              title={
                <div className={styles.tabTitle}>
                  <div>{type.title}</div>
                  <div className={styles.subTitle}>{type.sub_title}</div>
                </div>
              }
            />
          ))}
        </Tabs>

        {renderProducts()}
      </div>
    </div>
  );
};

export default ScorePage;
